<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Cart extends Model
{
    use HasFactory;

    protected $table = 'cart';

    protected $primaryKey = 'id';

    protected $fillable = ['customer_id', 'store_id', 'product_id', 'count'];

    public $timestamps = false;

    public function getList(array $params): array
    {
        $whereSql = self::conditions($params);

        $sql = "
            SELECT
                c.*,
                p.name,
                p.image_url,
                p.kcal,
                p.type_id,
                p.description,
                p.price,
                p.protein,
                p.carbon_water,
                p.meals,
                p.salt,
                p.fat,
                p.diversity,
                round(c.count * p.price) as total_price,
                round(c.count * p.pack_price) as total_pack_price
            FROM
                cart c
                LEFT JOIN product p ON p.id = c.product_id
            WHERE
                c.delete_flg = 0
                {$whereSql}
        ";
        return DB::select($sql);
    }

    public static function conditions(array $params): string
    {
        $whereSql = "";

        if (!empty($params['customer_id'])) {
            $whereSql .= "and c.customer_id = '{$params['customer_id']}'";
        }
        if (!empty($params['store_id'])) {
            $whereSql .= "and c.store_id = '{$params['store_id']}'";
        }

        return $whereSql;
    }
}
